#!/bin/bash

# ==============================================================================
# OS & Kernel Preparation Script for High-Performance MySQL
#
# This script should be run once as root before starting the main optimization
# framework. It configures kernel parameters, user limits, and other system-
# level settings for optimal database performance.
# ==============================================================================

if [[ $EUID -ne 0 ]]; then
   echo "错误: 此脚本必须以 root 身份运行。"
   exit 1
fi

echo "--- 1. 禁用防火墙和 SELinux ---"
systemctl stop firewalld
systemctl disable firewalld
if [ -f /etc/selinux/config ]; then
    sed -i 's/SELINUX=enforcing/SELINUX=disabled/g' /etc/selinux/config
    sed -i 's/SELINUX=permissive/SELINUX=disabled/g' /etc/selinux/config
fi
setenforce 0
echo "完成。"

echo "--- 2. 禁用透明大页 (Transparent Huge Pages) ---"
echo never > /sys/kernel/mm/transparent_hugepage/enabled
echo never > /sys/kernel/mm/transparent_hugepage/defrag
# Make it persistent across reboots
if ! grep -q "transparent_hugepage" /etc/rc.local; then
    echo 'echo never > /sys/kernel/mm/transparent_hugepage/enabled' >> /etc/rc.local
    echo 'echo never > /sys/kernel/mm/transparent_hugepage/defrag' >> /etc/rc.local
    chmod +x /etc/rc.local
fi
echo "完成。"

echo "--- 3. 设置 tuned-adm profile ---"
tuned-adm profile throughput-performance
echo "完成。"

echo "--- 4. 配置内核参数 (/etc/sysctl.conf) ---"
# Calculate memory-based values
# Using 251GiB RAM from your 'free -h' output
PHYSICAL_MEM_BYTES=$((251 * 1024 * 1024 * 1024))
# FIX: shmmax should be large enough for the total buffer pool size of all instances
# 4 instances * 52GB (Extreme) = 208GB. Let's set it to 220GB.
SHMMAX=$((220 * 1024 * 1024 * 1024))
SHMALL=$((${PHYSICAL_MEM_BYTES} / 4096)) # RAM size / page size
HUGEPAGES=$(( (${SHMMAX} / 1024 / 1024 / 2) + 1 )) # shmmax / 2MB Huge Page Size, +1 for safety

# Get mysql user's group ID for hugetlb
MYSQL_GID=$(id -g mysql 2>/dev/null)
if [ -z "$MYSQL_GID" ]; then
    echo "警告: 未找到 'mysql' 用户组。vm.hugetlb_shm_group 将不会被设置。"
    MYSQL_GID="<手动设置>"
fi

cat > /etc/sysctl.d/98-mysql-perf.conf <<EOF
# --- MySQL Performance Tuning ---
# Shared Memory
kernel.shmmax = ${SHMMAX}
kernel.shmall = ${SHMALL}
kernel.shmmni = 4096

# File System
fs.aio-max-nr = 1048576
fs.file-max = 6815744

# Kernel
kernel.sem = 250 32000 100 200

# Networking
net.ipv4.ip_local_port_range = 9000 65500
net.core.rmem_default = 262144
net.core.rmem_max = 4194304
net.core.wmem_default = 262144
net.core.wmem_max = 2097152

# VM Settings
vm.swappiness = 1
vm.nr_hugepages = ${HUGEPAGES}
vm.hugetlb_shm_group = ${MYSQL_GID}
EOF

# Apply settings
sysctl -p /etc/sysctl.d/98-mysql-perf.conf
echo "完成。配置文件: /etc/sysctl.d/98-mysql-perf.conf"


echo "--- 5. 配置用户资源限制 (/etc/security/limits.conf) ---"
LIMITS_CONFIG="/etc/security/limits.d/98-mysql-limits.conf"
cat > "$LIMITS_CONFIG" <<EOF
# --- Limits for MySQL User ---
mysql soft nofile 1024000
mysql hard nofile 1024000
mysql soft nproc 65535
mysql hard nproc 65535
mysql soft memlock unlimited
mysql hard memlock unlimited
mysql soft core unlimited
mysql hard core unlimited
mysql soft stack unlimited
mysql hard stack unlimited
EOF
echo "完成。配置文件: $LIMITS_CONFIG"
echo ""
echo "#####################################################################"
echo "#  系统级优化已完成。                                               #"
echo "#  为使所有更改完全生效（特别是SELinux和limits.conf），建议您重启服务器。#"
echo "#  重启后，您可以继续运行主优化脚本 find_best_mysql_config.sh。     #"
echo "#####################################################################"